<%--
  Created by IntelliJ IDEA.
  User: think
  Date: 2019/8/10
  Time: 17:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>微信扫码支付和支付回调websocket</title>
    <script type="text/javascript">
        var websocket = null;
        function connection() {
            if ("WebSocket" in window) {
                //获取订单ID
                var order_id = document.getElementById("order_id").value;
                // 打开一个 web socket
                websocket = new WebSocket("ws://"+document.location.host+"<%=request.getContextPath()%>/websocket/"+order_id);

                websocket.onopen = function () {
                    // Web Socket 已连接上，使用 send() 方法发送数据
                    fillData("建立连接了...");
                };

                websocket.onmessage = function (evt) {
                    fillData(evt.data);
                    //支付图片请见:webapp/payImage目录下图片
                    location.href = "http://www.baidu.com";//支付成功之后,跳转到百度页面...
                };

                websocket.onclose = function () {
                    // 关闭 websocket
                    fillData("连接关闭了...");
                };

                websocket.onerror = function () {
                    // 出现错误 websocket
                    fillData("出现错误了...");
                };

                window.onbeforeunload = function (){
                    //当浏览器关闭的时候,此处应该关联websocket连接,防止服务器出现异常
                    if(websocket != null){
                        websocket.close();
                    }
                }
            } else {
                // 浏览器不支持 WebSocket
                fillData("您的浏览器不支持 WebSocket!");
            }
        }

        /**
         * 根据websocket返回的消息填充
         * @param data
         */
        function fillData(data){
            document.getElementById("message").innerHTML = data;
        }
        // window.onload = connection();
    </script>
</head>
<body onload="connection()">
<input type="hidden" id="order_id" value="${order_id}"/>
当前是支付界面,订单号为:${order_id}<br>
请扫码支付:<br/>
<img src="<%=request.getContextPath()%>/payment/image"/>
<br/>
<br/>
<span id="message"></span>
</body>
</html>
